package com.youlu.campus.service.account.impl;

import com.alibaba.fastjson.JSON;
import com.mongodb.client.result.DeleteResult;
import com.youlu.campus.base.exception.BusinessException;
import com.youlu.campus.entity.UserAccountInfo;
import com.youlu.campus.service.account.UserAccountInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;


@Slf4j
@Service
public class UserAccountInfoServiceImpl implements UserAccountInfoService {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public UserAccountInfo get(String id) {
        log.info(":>>> 开始获取账户信息:{}", id);
        if (StringUtils.isNotBlank(id)) {
            log.error("账户信息为空");
            throw new BusinessException("账户信息为空");
        }
        Query query = new Query().addCriteria(Criteria.where("accountInfoId").is(id));
        UserAccountInfo u = mongoTemplate.findOne(query, UserAccountInfo.class);
        log.info(":>>> 用户:{} 账户信息为:{}", id, JSON.toJSONString(u));
        return u;
    }

    @Override
    public UserAccountInfo findBy(String mobile) {
        log.info(":>>> 开始获取账户信息mobile:{}", mobile);
        if (StringUtils.isNotBlank(mobile)) {
            log.error("手机号为空");
            throw new BusinessException("手机号为空");
        }
        Query query = new Query().addCriteria(Criteria.where("mobile").is(mobile));
        UserAccountInfo u = mongoTemplate.findOne(query, UserAccountInfo.class);
        log.info(":>>> 用户 mobile:{} 账户信息为:{}", mobile, JSON.toJSONString(u));
        return u;
    }

    @Override
    public UserAccountInfo create(UserAccountInfo req) {
        req.setId(null);
        req.setCreatedTime(new Date());
        req = mongoTemplate.insert(req);
        return req;
    }

    @Override
    public boolean update(UserAccountInfo req) {
        return false;
    }

    @Override
    public boolean delete(String id) {
        log.info(":>>> id:{}", id);
        if (StringUtils.isNotBlank(id)) {
            log.error("ID为空");
            throw new BusinessException("ID为空");
        }
        Query query = new Query().addCriteria(Criteria.where("accountInfoId").is(id));
        DeleteResult deleteResult = mongoTemplate.remove(query, UserAccountInfo.class);
        log.info(":>>> 删除:{} 用户结果:{}", id, deleteResult.getDeletedCount() > 0 ? true : false);
        return deleteResult.getDeletedCount() > 0 ? true : false;
    }
}
